﻿using System;
using System.ComponentModel;
using System.Deployment.Application;
using System.Windows.Forms;

namespace CloudShot.Utils
{
	public static class ApplicationUpdater
	{
		private static Form _mainForm;
		public static void InstallUpdateIfAvailable(Form mainForm)
		{
			//http://msdn.microsoft.com/en-us/library/ms404263.aspx
			if (!ApplicationDeployment.IsNetworkDeployed)
				return;

			_mainForm = mainForm;

			try
			{
				ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
				ad.CheckForUpdateCompleted += OnCheckOfUpdateCompleted;
				ad.CheckForUpdateAsync();
			}
			catch (Exception err)
			{
				ErrorsHelper.TraceError(err);
			}
		}

		private static void OnCheckOfUpdateCompleted(object sender, CheckForUpdateCompletedEventArgs e)
		{
			try
			{
				if (!e.UpdateAvailable)
					return;

				ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
				ad.UpdateCompleted += OnUpdateCompleted;
				ad.UpdateAsync();
			}
			catch (Exception err)
			{
				ErrorsHelper.TraceError(err);
			}
		}

		private static void OnUpdateCompleted(object sender, AsyncCompletedEventArgs e)
		{
			if (e.Cancelled)
				return;

			if (_mainForm == null)
				return;

			if (Application.OpenForms.Count > 1)//some forma are open
			{
				DialogResult result = MessageBox.Show(Application.ProductName + " has been updated." + Environment.NewLine + "Do you want to apply updates now?",
					Application.ProductName + " Updater", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

				if (result != DialogResult.Yes)
					return;
			}

			_mainForm.Invoke(new MethodInvoker(Application.Restart));
		}
	}
}